<script lang="ts" setup>
import { ref, reactive, onMounted, h } from 'vue';
import { useRouter } from 'vue-router';
import { 
  Card, Table, Button, Input, Space, Form, Select, DatePicker, 
  message, Tabs, Tag, Tooltip, Modal, Upload 
} from 'ant-design-vue';
import type { TableColumnsType, FormInstance } from 'ant-design-vue';
import type { UploadFile, UploadProps, RcFile } from 'ant-design-vue/es/upload/interface';
import {
  getSettlementListApi,
  getSettlementLandingCompanyOptionsApi,
  createSettlementApi,
  deleteSettlementApi,
  type SettlementApi
} from '#/api/core/settlement';
import {
  getTaskListApi,
  type TaskApi
} from '#/api/core/task';
import { 
  getSubSettlementListApi,
  type SubSettlementApi 
} from '#/api/core/sub-settlement';

interface SettlementRecord {
  id: string;
  settlement_number: string;
  settlement_name: string;
  task_name?: string;
  landing_company: string;
  total_amount: number;
  success_amount: number;
  total_count: number;
  success_count: number;
  status: 'pending_submit' | 'distributing' | 'completed' | 'cancelled' | 'distribute_failed' | 'partial_failed';
  status_display: string;
  deliverables?: string;
  remarks?: string;
  success_rate: number;
  amount_success_rate: number;
  created_at: string;
}

interface TaskOption {
  id: number;
  name: string;
}

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  pageSizeOptions: string[];
  showTotal: (total: number, range: [number, number]) => string;
}

// 路由
const router = useRouter();

// 响应式数据
const loading = ref(false);
const deletingSettlementId = ref<string | null>(null);
const taskLoading = ref(false);
const dataSource = ref<SettlementRecord[]>([]);
const taskOptions = ref<TaskOption[]>([]);
const activeTab = ref('settlement-list');

// 子结算单相关数据
const subSettlementLoading = ref(false);
const subSettlements = ref<SubSettlementApi.SubSettlementRecord[]>([]);

// 子结算单搜索表单
const subSettlementSearchForm = reactive({
  sub_settlement_id: '',
  settlement_id: '',
  name: '',
  phone: '',
  id_card: '',
  status: undefined as string | undefined,
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
  distribute_start_date: undefined as string | undefined,
  distribute_end_date: undefined as string | undefined,
});

// 子结算单分页数据
const subSettlementPagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 子结算单状态选项
const subSettlementStatusOptions = [
  { value: 'verifying', label: '验证中' },
  { value: 'pending_submit', label: '待提交' },
  { value: 'pending_distribute', label: '待发放' },
  { value: 'distributing', label: '发放中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' },
  { value: 'distribute_failed', label: '发放失败' },
  { value: 'verify_failed', label: '验证失败' },
  { value: 'refunded', label: '已退票' }
];

const landingCompanyOptions = ref<Array<{ label: string; value: string; raw: SettlementApi.LandingCompanyOption }>>([]);

// 子结算单表格列定义
const subSettlementColumns: TableColumnsType<SubSettlementApi.SubSettlementRecord> = [
  {
    title: '子结算单ID',
    key: 'sub_settlement_number',
    width: 130,
    ellipsis: true,
    customRender: ({ record }) => {
      return h(Tooltip, 
        { title: `完整ID: ${record.id}` }, 
        () => record.sub_settlement_number
      );
    }
  },
  {
    title: '结算单ID',
    key: 'settlement_number',
    width: 130,
    ellipsis: true,
    customRender: ({ record }) => {
      return record.settlement?.settlement_number || '-';
    }
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
    ellipsis: true,
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
    ellipsis: true,
  },
  {
    title: '身份证号',
    dataIndex: 'id_card',
    key: 'id_card',
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => {
      if (!text) return '-';
      return text.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2');
    },
  },
  {
    title: '银行账号',
    dataIndex: 'bank_account',
    key: 'bank_account',
    width: 140,
    ellipsis: true,
    customRender: ({ text }) => {
      if (!text) return '-';
      return text.replace(/(\d{4})\d*(\d{4})/, '$1****$2');
    },
  },
  {
    title: '开户银行',
    dataIndex: 'bank_name',
    key: 'bank_name',
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => text || '-',
  },
  {
    title: '结算前金额',
    dataIndex: 'pre_settlement_amount',
    key: 'pre_settlement_amount',
    width: 120,
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '佣金',
    dataIndex: 'commission',
    key: 'commission',
    width: 100,
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '服务费',
    dataIndex: 'service_fee',
    key: 'service_fee',
    width: 100,
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusColorMap: Record<string, string> = {
        'verifying': 'processing',
        'pending_submit': 'default',
        'pending_distribute': 'warning',
        'distributing': 'processing',
        'completed': 'success',
        'cancelled': 'default',
        'distribute_failed': 'error',
        'verify_failed': 'error',
        'refunded': 'default'
      };
      
      return h(Tag, 
        { color: statusColorMap[record.status] }, 
        () => record.status_display
      );
    },
  },
  {
    title: '备注',
    dataIndex: 'payment_remarks',
    key: 'payment_remarks',
    width: 120,
    ellipsis: true,
    customRender: ({ text }) => {
      return text ? h(Tooltip, { title: text }, () => '查看') : '-';
    },
  },
  {
    title: '电子回单',
    dataIndex: 'electronic_receipt',
    key: 'electronic_receipt',
    width: 100,
    customRender: ({ text }) => {
      return text ? h(Tooltip, { title: '点击查看电子回单' }, () => '查看') : '-';
    },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 160,
    customRender: ({ text }) => {
      return new Date(text).toLocaleString('zh-CN');
    },
  },
  {
    title: '发放时间',
    dataIndex: 'distributed_at',
    key: 'distributed_at',
    width: 160,
    customRender: ({ text }) => {
      return text ? new Date(text).toLocaleString('zh-CN') : '-';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right',
    customRender: ({ record }) => {
      return h(Button, { 
        type: 'link', 
        size: 'small',
        onClick: () => handleViewSettlement(record.settlement_id)
      }, '查看结算单');
    },
  },
];

// 搜索表单
const searchForm = reactive({
  settlement_id: '',
  settlement_name: '',
  task_id: undefined as number | undefined,
  status: undefined as string | undefined,
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
});

// 分页数据
const pagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

// 状态选项
const statusOptions = [
  { value: 'pending_submit', label: '待提交' },
  { value: 'distributing', label: '发放中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' },
  { value: 'distribute_failed', label: '发放失败' },
  { value: 'partial_failed', label: '部分失败' }
];

// 表格列定义
const columns: TableColumnsType<SettlementRecord> = [
  {
    title: '结算单ID',
    dataIndex: 'settlement_number',
    key: 'settlement_number',
    width: 150,
    ellipsis: true,
    customRender: ({ record }) => {
      return h(Tooltip, 
        { title: `完整ID: ${record.id}` }, 
        () => record.settlement_number
      );
    }
  },
  {
    title: '结算单名称',
    dataIndex: 'settlement_name',
    key: 'settlement_name',
    width: 200,
    ellipsis: true,
  },
  {
    title: '任务名称',
    key: 'task_name',
    width: 150,
    ellipsis: true,
    customRender: ({ record }) => {
      return record.task_name || '-';
    },
  },
  {
    title: '落地公司',
    dataIndex: 'landing_company',
    key: 'landing_company',
    width: 150,
    ellipsis: true,
  },
  {
    title: '总金额',
    dataIndex: 'total_amount',
    key: 'total_amount',
    width: 120,
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '结算成功金额',
    dataIndex: 'success_amount',
    key: 'success_amount',
    width: 140,
    customRender: ({ text }) => `¥${Number(text).toLocaleString()}`,
  },
  {
    title: '总笔数',
    dataIndex: 'total_count',
    key: 'total_count',
    width: 100,
    customRender: ({ text }) => `${text}笔`,
  },
  {
    title: '成功笔数',
    dataIndex: 'success_count',
    key: 'success_count',
    width: 100,
    customRender: ({ text }) => `${text}笔`,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }) => {
      const statusColorMap: Record<string, string> = {
        'pending_submit': 'default',
        'distributing': 'processing',
        'completed': 'success',
        'cancelled': 'default',
        'distribute_failed': 'error',
        'partial_failed': 'warning'
      };
      
      return h(Tag, 
        { color: statusColorMap[record.status] }, 
        () => record.status_display
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 160,
    customRender: ({ text }) => {
      return new Date(text).toLocaleString('zh-CN');
    },
  },
  {
    title: '交付物',
    dataIndex: 'deliverables',
    key: 'deliverables',
    width: 120,
    ellipsis: true,
    customRender: ({ text }) => {
      return text ? h(Tooltip, { title: text }, () => '查看') : '-';
    },
  },
  {
    title: '备注',
    dataIndex: 'remarks',
    key: 'remarks',
    width: 120,
    ellipsis: true,
    customRender: ({ text }) => {
      return text ? h(Tooltip, { title: text }, () => '查看') : '-';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    customRender: ({ record }) => {
      const actions = [
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleViewDetail(record.id),
          },
          () => '查看详情',
        ),
      ];

      const lockedStatuses = ['发放中', '已完成', '已取消', '发放失败', '部分失败'];

      if (!lockedStatuses.includes(record.status)) {
        actions.push(
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              danger: true,
              onClick: () => handleDeleteSettlement(record),
            },
            () => '删除',
          ),
        );
      }

      return h(Space, { size: 'small' }, () => actions);
    },
  },
];

// 获取列表数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    const params = {
      page: pagination.current,
      per_page: pagination.pageSize,
      settlement_id: searchForm.settlement_id.trim() || undefined,
      settlement_name: searchForm.settlement_name.trim() || undefined,
      task_id: searchForm.task_id,
      status: searchForm.status,
      start_date: searchForm.start_date,
      end_date: searchForm.end_date,
    };
    
    console.log('📤 发送请求参数:', params);
    
    const response = await getSettlementListApi(params);
    console.log('📥 API响应:', response);
    
    dataSource.value = response.data || [];
    pagination.total = response.total || 0;
    pagination.current = response.current_page || 1;
    
    console.log('✅ 数据更新成功:', {
      count: dataSource.value.length,
      total: pagination.total,
      current: pagination.current
    });
  } catch (error) {
    console.error('❌ 请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    dataSource.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取任务选项
const fetchTaskOptions = async () => {
  try {
    taskLoading.value = true;
    const response = await getTaskListApi({});

    // 转换为任务选项格式
    // 注意：requestClient已经处理了后端的{code,message,data}格式，直接返回data字段内容
    taskOptions.value = response.data?.map((task: TaskApi.TaskRecord) => ({
      id: task.id,
      name: task.name
    })) || [];
  } catch (error) {
    console.error('获取任务列表失败:', error);
  } finally {
    taskLoading.value = false;
  }
};

const fetchLandingCompanyOptions = async () => {
  try {
    const response = await getSettlementLandingCompanyOptionsApi();
    landingCompanyOptions.value = (response || []).map((item) => ({
      label: item.label ?? item.name ?? String(item.value ?? ''),
      value: String(item.value ?? item.code ?? item.name ?? ''),
      raw: item,
    }));
    if (landingCompanyOptions.value.length > 0) {
      uploadFormState.landing_company = landingCompanyOptions.value[0].value;
    }
  } catch (error) {
    console.error('获取落地公司选项失败:', error);
  }
};

// 搜索操作
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.settlement_id = '';
  searchForm.settlement_name = '';
  searchForm.task_id = undefined;
  searchForm.status = undefined;
  searchForm.start_date = undefined;
  searchForm.end_date = undefined;
  pagination.current = 1;
  fetchData();
};

// 上传结算单（占位）
const uploadModalVisible = ref(false);
const uploadSaving = ref(false);
const uploadFormRef = ref<FormInstance>();
const uploadFormState = reactive({
  task_id: undefined as number | undefined,
  landing_company: '',
  settlement_file: null as RcFile | null,
  deliverable_file: null as RcFile | null,
  remarks: '',
});
const settlementFileList = ref<UploadFile[]>([]);
const deliverableFileList = ref<UploadFile[]>([]);

const settlementUploadProps: UploadProps = {
  beforeUpload: (file) => {
    if (file.size > 20 * 1024 * 1024) {
      message.error('结算单文件大小不能超过 20 MB');
      return Upload.LIST_IGNORE;
    }
    uploadFormState.settlement_file = file as RcFile;
    settlementFileList.value = [file];
    return false;
  },
  onRemove: () => {
    uploadFormState.settlement_file = null;
    settlementFileList.value = [];
  },
  maxCount: 1,
  accept: '.xlsx,.xls',
};

const deliverableUploadProps: UploadProps = {
  beforeUpload: (file) => {
    if (file.size > 50 * 1024 * 1024) {
      message.error('交付物文件大小不能超过 50 MB');
      return Upload.LIST_IGNORE;
    }
    uploadFormState.deliverable_file = file as RcFile;
    deliverableFileList.value = [file];
    return false;
  },
  onRemove: () => {
    uploadFormState.deliverable_file = null;
    deliverableFileList.value = [];
  },
  maxCount: 1,
};

const uploadFormRules = {
  task_id: [{ required: true, message: '请选择任务' }],
  landing_company: [{ required: true, message: '请选择落地公司' }],
};

const resetUploadForm = () => {
  uploadFormRef.value?.resetFields();
  uploadFormState.task_id = undefined;
  uploadFormState.landing_company = landingCompanyOptions.value[0]?.value ?? '';
  uploadFormState.settlement_file = null;
  uploadFormState.deliverable_file = null;
  uploadFormState.remarks = '';
  settlementFileList.value = [];
  deliverableFileList.value = [];
};

const handleUpload = () => {
  resetUploadForm();
  uploadModalVisible.value = true;
};

const handleUploadModalCancel = () => {
  uploadModalVisible.value = false;
  resetUploadForm();
};

const submitUploadSettlement = async () => {
  if (!uploadFormRef.value) return;
  try {
    await uploadFormRef.value.validate();
    if (!uploadFormState.settlement_file) {
      message.warning('请上传结算单文件');
      return;
    }

    const formData = new FormData();
    formData.append('task_id', String(uploadFormState.task_id));
    formData.append('landing_company', uploadFormState.landing_company.trim());
    formData.append('settlement_file', uploadFormState.settlement_file);
    if (uploadFormState.deliverable_file) {
      formData.append('deliverable_file', uploadFormState.deliverable_file);
    }
    if (uploadFormState.remarks) {
      formData.append('remarks', uploadFormState.remarks.trim());
    }

    uploadSaving.value = true;
    await createSettlementApi(formData);
    message.success('结算单上传成功');
    uploadModalVisible.value = false;
    resetUploadForm();
    fetchData();
  } catch (error: any) {
    if (error?.errorFields) {
      return;
    }
    console.error('结算单上传失败', error);
    message.error(error?.message || '结算单上传失败，请稍后重试');
  } finally {
    uploadSaving.value = false;
  }
};

// 导出数据（占位）
const handleExport = () => {
  message.info('导出功能开发中...');
};

// 查看详情
const handleViewDetail = (id: string) => {
  router.push(`/settlement/settlement-detail/${id}`);
};

// 编辑
const handleEdit = (id: string) => {
  message.info(`编辑 ID: ${id}，功能开发中...`);
};

// 分页变化处理
const handleTableChange = (paginationParams: any) => {
  pagination.current = paginationParams.current;
  pagination.pageSize = paginationParams.pageSize;
  fetchData();
};

// 时间范围选择处理
const handleDateRangeChange = (dates: any, dateStrings: string[]) => {
  searchForm.start_date = dateStrings[0] || undefined;
  searchForm.end_date = dateStrings[1] || undefined;
};

// Tab切换处理
const handleTabChange = (key: string) => {
  activeTab.value = key;
  if (key === 'settlement-list') {
    fetchData();
  } else if (key === 'settlement-detail') {
    fetchSubSettlements();
  }
};

// 获取子结算单列表数据
const fetchSubSettlements = async () => {
  try {
    subSettlementLoading.value = true;
    
    const params = {
      page: subSettlementPagination.current,
      per_page: subSettlementPagination.pageSize,
      sub_settlement_id: subSettlementSearchForm.sub_settlement_id.trim() || undefined,
      settlement_id: subSettlementSearchForm.settlement_id.trim() || undefined,
      name: subSettlementSearchForm.name.trim() || undefined,
      phone: subSettlementSearchForm.phone.trim() || undefined,
      id_card: subSettlementSearchForm.id_card.trim() || undefined,
      status: subSettlementSearchForm.status,
      start_date: subSettlementSearchForm.start_date,
      end_date: subSettlementSearchForm.end_date,
      distribute_start_date: subSettlementSearchForm.distribute_start_date,
      distribute_end_date: subSettlementSearchForm.distribute_end_date,
    };
    
    console.log('📤 发送子结算单请求参数:', params);
    
    const response = await getSubSettlementListApi(params);
    console.log('📥 子结算单API响应:', response);
    
    subSettlements.value = response.data || [];
    subSettlementPagination.total = response.total || 0;
    subSettlementPagination.current = response.current_page || 1;
    
    console.log('✅ 子结算单数据更新成功:', {
      count: subSettlements.value.length,
      total: subSettlementPagination.total,
      current: subSettlementPagination.current
    });
  } catch (error) {
    console.error('❌ 子结算单请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    subSettlements.value = [];
    subSettlementPagination.total = 0;
  } finally {
    subSettlementLoading.value = false;
  }
};

// 子结算单搜索操作
const handleSubSettlementSearch = () => {
  subSettlementPagination.current = 1;
  fetchSubSettlements();
};

// 重置子结算单搜索条件
const handleSubSettlementReset = () => {
  subSettlementSearchForm.sub_settlement_id = '';
  subSettlementSearchForm.settlement_id = '';
  subSettlementSearchForm.name = '';
  subSettlementSearchForm.phone = '';
  subSettlementSearchForm.id_card = '';
  subSettlementSearchForm.status = undefined;
  subSettlementSearchForm.start_date = undefined;
  subSettlementSearchForm.end_date = undefined;
  subSettlementSearchForm.distribute_start_date = undefined;
  subSettlementSearchForm.distribute_end_date = undefined;
  subSettlementPagination.current = 1;
  fetchSubSettlements();
};

// 子结算单导出数据（占位）
const handleSubSettlementExport = () => {
  message.info('导出功能开发中...');
};

// 查看结算单详情
const handleViewSettlement = (settlementId: string) => {
  router.push(`/settlement/settlement-detail/${settlementId}`);
};

const handleDeleteSettlement = (record: SettlementRecord) => {
  const lockedStatuses: SettlementRecord['status'][] = [
    'distributing',
    'completed',
    'cancelled',
    'distribute_failed',
    'partial_failed',
  ];

  if (lockedStatuses.includes(record.status)) {
    message.warning('该状态的结算单无法删除');
    return;
  }

  Modal.confirm({
    title: '确认删除该结算单？',
    content: '删除后将无法恢复，请确认该结算单尚未进入发放中状态。',
    okText: '删除',
    okButtonProps: { danger: true },
    cancelText: '取消',
    async onOk() {
      deletingSettlementId.value = record.id;
      try {
        await deleteSettlementApi(record.id);
        message.success('结算单删除成功');
        fetchData();
      } catch (error) {
        console.error('删除结算单失败:', error);
        const errorMessage =
          error?.response?.data?.message || error?.message || '删除结算单失败，请稍后重试';
        message.error(errorMessage);
      } finally {
        deletingSettlementId.value = null;
      }
    },
  });
};

// 子结算单分页变化处理
const handleSubSettlementTableChange = (paginationParams: any) => {
  subSettlementPagination.current = paginationParams.current;
  subSettlementPagination.pageSize = paginationParams.pageSize;
  fetchSubSettlements();
};

// 子结算单时间范围选择处理
const handleSubSettlementDateRangeChange = (dates: any, dateStrings: string[]) => {
  subSettlementSearchForm.start_date = dateStrings[0] || undefined;
  subSettlementSearchForm.end_date = dateStrings[1] || undefined;
};

// 子结算单发放时间范围选择处理
const handleDistributeDateRangeChange = (dates: any, dateStrings: string[]) => {
  subSettlementSearchForm.distribute_start_date = dateStrings[0] || undefined;
  subSettlementSearchForm.distribute_end_date = dateStrings[1] || undefined;
};

// 组件挂载时加载数据
onMounted(() => {
  fetchTaskOptions();
  fetchLandingCompanyOptions();
  fetchData();
});
</script>

<template>
  <div class="p-5">
    <Card>
      <Tabs v-model:activeKey="activeTab" @change="handleTabChange">
        <!-- 第一个Tab：业务结算 -->
        <Tabs.TabPane key="settlement-list" tab="业务结算">
          <!-- 搜索区域 -->
          <div class="mb-4">
            <Form layout="inline" :model="searchForm">
              <Form.Item label="结算单ID" name="settlement_id">
                <Input
                  v-model:value="searchForm.settlement_id"
                  placeholder="请输入结算单ID"
                  style="width: 160px"
                  allowClear
                  @pressEnter="handleSearch"
                />
              </Form.Item>
              
              <Form.Item label="结算单名称" name="settlement_name">
                <Input
                  v-model:value="searchForm.settlement_name"
                  placeholder="请输入结算单名称"
                  style="width: 160px"
                  allowClear
                  @pressEnter="handleSearch"
                />
              </Form.Item>
              
              <Form.Item label="任务" name="task_id">
                <Select
                  v-model:value="searchForm.task_id"
                  placeholder="请选择任务"
                  style="width: 160px"
                  allowClear
                  :loading="taskLoading"
                  showSearch
                  optionFilterProp="label"
                >
                  <Select.Option 
                    v-for="task in taskOptions" 
                    :key="task.id" 
                    :value="task.id"
                    :label="task.name"
                  >
                    {{ task.name }}
                  </Select.Option>
                </Select>
              </Form.Item>
              
              <Form.Item label="状态" name="status">
                <Select
                  v-model:value="searchForm.status"
                  placeholder="请选择状态"
                  style="width: 120px"
                  allowClear
                >
                  <Select.Option 
                    v-for="status in statusOptions" 
                    :key="status.value" 
                    :value="status.value"
                  >
                    {{ status.label }}
                  </Select.Option>
                </Select>
              </Form.Item>
              
              <Form.Item label="创建时间" name="date_range">
                <DatePicker.RangePicker
                  style="width: 240px"
                  @change="handleDateRangeChange"
                />
              </Form.Item>
              
              <Form.Item>
                <Space>
                  <Button 
                    type="primary" 
                    @click="handleSearch"
                    :loading="loading"
                  >
                    查询
                  </Button>
                  <Button @click="handleReset">
                    重置
                  </Button>
                  <Button @click="handleUpload">
                    上传结算单
                  </Button>
                  <Button @click="handleExport">
                    导出数据
                  </Button>
                  <a
                    class="ant-btn"
                    href="/settlement-template.xlsx"
                    download
                  >
                    下载结算单模板
                  </a>
                </Space>
              </Form.Item>
            </Form>
          </div>
          
      <!-- 数据表格 -->
      <Table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        :scroll="{ x: 1800 }"
        @change="handleTableChange"
      />

      <Modal
        v-model:open="uploadModalVisible"
        title="上传结算单"
        :confirm-loading="uploadSaving"
        @ok="submitUploadSettlement"
        @cancel="handleUploadModalCancel"
        destroy-on-close
      >
        <Form ref="uploadFormRef" :model="uploadFormState" :rules="uploadFormRules" layout="vertical">
          <Form.Item label="任务" name="task_id">
            <Select
              v-model:value="uploadFormState.task_id"
              placeholder="请选择任务"
              :loading="taskLoading"
              show-search
              optionFilterProp="label"
            >
              <Select.Option
                v-for="task in taskOptions"
                :key="task.id"
                :value="task.id"
                :label="task.name"
              >
                {{ task.name }}
              </Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label="落地公司" name="landing_company">
            <Select
              v-model:value="uploadFormState.landing_company"
              :options="landingCompanyOptions"
              disabled
            />
          </Form.Item>

          <Form.Item label="结算单文件" required>
            <Upload v-bind="settlementUploadProps" :file-list="settlementFileList">
              <Button type="dashed">选择结算文件</Button>
            </Upload>
            <p class="text-xs text-gray-500 mt-2">支持 xlsx / xls，文件大小不超过 20 MB。</p>
          </Form.Item>

          <Form.Item label="交付物文件">
            <Upload v-bind="deliverableUploadProps" :file-list="deliverableFileList">
              <Button type="dashed">选择交付物 (可选)</Button>
            </Upload>
            <p class="text-xs text-gray-500 mt-2">可上传交付物附件，大小不超过 50 MB。</p>
          </Form.Item>

          <Form.Item label="备注" name="remarks">
            <Input.TextArea
              v-model:value="uploadFormState.remarks"
              :rows="3"
              placeholder="请输入备注 (可选)"
              maxlength="500"
              show-count
            />
          </Form.Item>
        </Form>
      </Modal>
        </Tabs.TabPane>
        
        <!-- 第二个Tab：结算单详情 -->
        <Tabs.TabPane key="settlement-detail" tab="结算单详情">
          <!-- 搜索区域 -->
          <div class="mb-4">
            <Form layout="inline" :model="subSettlementSearchForm">
              <Form.Item label="子结算单ID" name="sub_settlement_id">
                <Input
                  v-model:value="subSettlementSearchForm.sub_settlement_id"
                  placeholder="请输入子结算单ID"
                  style="width: 160px"
                  allowClear
                  @pressEnter="handleSubSettlementSearch"
                />
              </Form.Item>
              
              <Form.Item label="结算单ID" name="settlement_id">
                <Input
                  v-model:value="subSettlementSearchForm.settlement_id"
                  placeholder="请输入结算单ID"
                  style="width: 160px"
                  allowClear
                  @pressEnter="handleSubSettlementSearch"
                />
              </Form.Item>
              
              <Form.Item label="姓名" name="name">
                <Input
                  v-model:value="subSettlementSearchForm.name"
                  placeholder="请输入姓名"
                  style="width: 120px"
                  allowClear
                  @pressEnter="handleSubSettlementSearch"
                />
              </Form.Item>
              
              <Form.Item label="手机号" name="phone">
                <Input
                  v-model:value="subSettlementSearchForm.phone"
                  placeholder="请输入手机号"
                  style="width: 140px"
                  allowClear
                  @pressEnter="handleSubSettlementSearch"
                />
              </Form.Item>
              
              <Form.Item label="身份证号" name="id_card">
                <Input
                  v-model:value="subSettlementSearchForm.id_card"
                  placeholder="请输入身份证号"
                  style="width: 160px"
                  allowClear
                  @pressEnter="handleSubSettlementSearch"
                />
              </Form.Item>
              
              <Form.Item label="状态" name="status">
                <Select
                  v-model:value="subSettlementSearchForm.status"
                  placeholder="请选择状态"
                  style="width: 120px"
                  allowClear
                >
                  <Select.Option 
                    v-for="status in subSettlementStatusOptions" 
                    :key="status.value" 
                    :value="status.value"
                  >
                    {{ status.label }}
                  </Select.Option>
                </Select>
              </Form.Item>
              
              <Form.Item label="创建时间" name="date_range">
                <DatePicker.RangePicker
                  style="width: 240px"
                  @change="handleSubSettlementDateRangeChange"
                />
              </Form.Item>
              
              <Form.Item label="发放时间" name="distribute_date_range">
                <DatePicker.RangePicker
                  style="width: 240px"
                  @change="handleDistributeDateRangeChange"
                />
              </Form.Item>
              
              <Form.Item>
                <Space>
                  <Button 
                    type="primary" 
                    @click="handleSubSettlementSearch"
                    :loading="subSettlementLoading"
                  >
                    查询
                  </Button>
                  <Button @click="handleSubSettlementReset">
                    重置
                  </Button>
                  <Button @click="handleSubSettlementExport">
                    导出数据
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
          
          <!-- 数据表格 -->
          <Table
            :columns="subSettlementColumns"
            :data-source="subSettlements"
            :loading="subSettlementLoading"
            :pagination="subSettlementPagination"
            row-key="id"
            :scroll="{ x: 2000 }"
            @change="handleSubSettlementTableChange"
          />
        </Tabs.TabPane>
      </Tabs>
    </Card>
  </div>
</template>

<style scoped>
.ant-table-tbody > tr > td {
  padding: 12px 8px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>
